﻿using System;
using System.Reflection;

namespace FDStudio.Core.Extensions
{
    /*
     CreatedOn: 2018-01-31
     CreatedBy: Jackie Lee(天宇遊龍)
     */
    /// <summary>
    /// 对象扩展
    /// </summary>
    public static class ObjectExtension
    {
        /// <summary>
        /// 对象转long
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static long ToLong(this object obj)
        {
            if (obj == DBNull.Value)
                return 0;
            return Convert.ToInt64(obj);
        }

        /// <summary>
        /// 对象转Int
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static int ToInt(this object obj)
        {
            if (obj == DBNull.Value)
                return 0;
            return Convert.ToInt32(obj);
        }

        /// <summary>
        /// 对象转String
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ConvertToString(this object obj)
        {
            if (obj == DBNull.Value)
                return string.Empty;
            return Convert.ToString(obj);
        }

        /// <summary>
        /// 对象转String
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool ToBoolean(this object obj)
        {
            if (obj == DBNull.Value)
                return false;
            return Convert.ToBoolean(obj);
        }

        /// <summary>
        /// 复制对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T Clone<T>(this T obj) where T : class, new()
        {
            var props = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
            var instance = Activator.CreateInstance<T>();
            foreach (var prop in props)
            {
                prop.SetValue(instance, prop.GetValue(obj));
            }
            return instance;
        }
    }
}
